/*
	练习7-6: 编写一个程序，比较两个文件并打印它们第一个不相同的行
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAXLEN 100

int main(int argc, char *argv[])
{
//	int err;
        FILE *fp1, *fp2;
	char *pfName1, *pfName2;
        char temp1[MAXLEN], temp2[MAXLEN];
        
	if(argc == 1)
	{
		pfName1 = (char *)malloc(sizeof(char) * MAXLEN);
                pfName2 = (char *)malloc(sizeof(char) * MAXLEN);
                printf("请输入第一个文件名： ");
                scanf("%s", pfName1);
                printf("请输入第二个文件名： ");
                scanf("%s", pfName2);
	}
        else if(argc == 3)
        {
                pfName1 = argv[1];
                pfName2 = argv[2];
        }
        else 
        {
                fprintf(stderr, "%s: Incorrect number of parameters. \n", argv[0]);
                exit(1);
        }
        
        if((fp1 = fopen(pfName1, "r")) == NULL || (fp2 = fopen(pfName2, "r")) == NULL)
        {
                fprintf(stderr, "%s: can't open %s. \n", argv[0], (fp1 == NULL ? pfName1 : pfName2));
                exit(2);
        }
        
        while(1)
        {
                if(fgets(temp1, MAXLEN, fp1) == NULL)           // fgets 函数会读取换行符
                        strcpy(temp1, "EOF");
                if(fgets(temp2, MAXLEN, fp2) == NULL)       
                        strcpy(temp2, "EOF");
                
                if(strcmp(temp1, temp2))
                        break;
                if(!strcmp(temp1, "EOF") && !strcmp(temp2, "EOF"))
                        break;
        }
//	printf("%d\n", err);
        printf("%s: %s\n", pfName1, temp1);
        printf("%s: %s\n", pfName2, temp2);
	
	if(argc == 1)
	{
		free(pfName1);
		free(pfName2);
	}       
 
        fclose(fp1);
        fclose(fp2);
        return 0;
}
